package em.ctrl;

import base.ctrl.BaseController;
import base.jfinal.PermissionInterceptor;
import base.jfinal.anatation.RouteBind;
import base.util.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import em.model.*;
import em.program.imp.OtherData;
import em.program.imp.RealData;
import em.util.CommonTools;
import em.util.TermUtil;
import em.util.ConstUtil;

import java.util.*;
import java.util.stream.Collectors;

@RouteBind(path = "eqpt")
public class EqptCtrl extends BaseController {

    /**
     * 查找设备
     *
     * @return 设备信息
     */
    public void getEqptById() {
        ViewEqptList viewEqptList = ViewEqptList.dao.findById(getPara("eqptId"));
        viewEqptList.put("originaleqptCode", viewEqptList.getStr("EqptCode"));
        this.renderJson(viewEqptList);
    }

    /**
     * 设备锁机
     */
    @Before(Tx.class)
    public void EqptLock() {
        String result = "", termCode = "",strLockOrg="";
        Boolean bFlag = false;
        int ii = 0;
        try {
            Eqpt eqpt;
            synchronized (ConstUtil.LOCK_LOCKOBJECT) {
                Map map=getParas();
                eqpt = Eqpt.dao.findById(map.get("eqptId"));
                strLockOrg = eqpt.getStr("lockOrg");//取得锁机的组织
                List<String> list = Arrays.asList(strLockOrg.split(","));
                if (list.size() == 0 || CommonTools.getInstance().isBlank(strLockOrg)) {//发送开机指令
                    strLockOrg = map.get("GlobalOrgId").toString();
                    List<Record> record = Db.find("select termcode from em_eqpt_data where EqptId=? and termcode is not null order by LastRunTime DESC", map.get("eqptId"));
                    for (Record r : record) {//给终端下发开机指令
                        termCode += r.getStr("termcode") + ";";
                        Integer tnum = TermUtil.TermCodeXOR(r.getStr("termcode"));
                        result = OtherData.getInstance().getData(tnum.toString(), 10, String.format(ConstUtil.ACTION_10, tnum,10001, 1), 0);
                    }
                } else if (!list.contains(map.get("GlobalOrgId").toString())) {
                    strLockOrg += "," + map.get("GlobalOrgId").toString();
                }
                strLockOrg=strLockOrg.indexOf(",")==0?strLockOrg.substring(1):strLockOrg;
                eqpt.set("lockOrg", strLockOrg.trim()).set("updateDate", DateUtil.getInstance().getCurrentDate()).update();
            }
            new Logger().set("AccountId", getParaToInt("GlobalAccId")).set("Model", "设备管理").set("Operation", "设备锁机")
                    .set("Desc", "设备编号:" + eqpt.getStr("eqptCode") + ",终端编号:" + termCode).set("SoureIp", this.getRequest().getRemoteAddr()).save();
            renderJson("{\"err\":0}");
        } catch (Exception e) {
            renderJson("{\"err\":1}");
            throw e;
        }
    }

    /**
     * 设备解锁
     */
    @Before(Tx.class)
    public void EqptLockOut() {
        Integer tnum = 0;
        String termCode = "",result = "";
        int ii = 0;
        try {
            Eqpt eqpt;
            synchronized (ConstUtil.LOCK_LOCKOBJECT) {
                Map map=getParas();
                eqpt = Eqpt.dao.findById(map.get("eqptId"));
                List<String> list1 = Arrays.asList(eqpt.getStr("lockOrg").split(","));//取得所有锁机的组织
                ArrayList<String> list=new ArrayList<>(list1);

                if(list.contains(map.get("GlobalOrgId").toString())) {//有锁机组织
                    list.remove(map.get("GlobalOrgId").toString());//直接
                    if (list.size() == 0) {//当是最后一个时,则发送解锁指令
                        List<Record> record = Db.find("select termcode from em_eqpt_data where EqptId=? and termcode is not null order by LastRunTime DESC", map.get("eqptId"));
                        for (Record r : record) {
                            termCode += r.getStr("termcode") + ";";
                            tnum = TermUtil.TermCodeXOR(r.getStr("termcode"));
                            OtherData.getInstance().getData(tnum.toString(), 10, String.format(ConstUtil.ACTION_10, tnum,10002, 2), 0);
                        }
                    }
                    result = list.stream().collect(Collectors.joining(","));
                    eqpt.set("lockOrg", result.trim()).set("updateDate",DateUtil.getInstance().getCurrentDate()).update();
                }
                new Logger().set("AccountId", getParaToInt("GlobalAccId")).set("Model", "设备管理").set("Operation", "设备解锁")
                        .set("Desc", "设备编号:" + eqpt.getStr("eqptCode") + ",终端编号:" + termCode).set("SoureIp", this.getRequest().getRemoteAddr()).save();
            }
            renderJson("{\"err\":0}");
        } catch (Exception e) {
            renderJson("{\"err\":1}");
            throw e;
        }
    }

    /**
     * 实时工况
     */
    @Clear({PermissionInterceptor.class})
    public void getRealWorking() {
        JSONObject errJson=new JSONObject();
        Map<String, Object> map = getParas();
        Integer TNC = TermUtil.TermCodeXOR(map.get("termCode").toString());
        if(TNC==0){
            renderJson(String.format(ConstUtil.ERROR_ACTION, 3));
        } else if (map.containsKey("end")) {
            RealData.getInstance().stopRealAction(TNC.toString());
            renderJson(String.format(ConstUtil.ERROR_ACTION, 0));
        } else {
            String str= RealData.getInstance().getData(TNC.toString(),20);
            errJson = JSONObject.parseObject(str);
        }
        renderJson(errJson);
    }

    /**
     * 查找设备GPS坐标
     */
    public void getEqptGpsList() {
        Map<String, Object> map = getParas();
        if (!map.containsKey("orgId")) {
            map.put("orgId", getParaToInt("GlobalOrgId"));
        }
        List<Record> lstData = Db.find(CommonTools.getInstance().getSql("eqpt.getEqptGpsList", map));
        renderJson(lstData);
    }
}
